class Solution
{
public:
    vector<int> findClosestElements(vector<int> &arr, int k, int x)
    {
        int n = arr.size();
        int left = 0;
        int right = n - 1;
        while (left < right)
        {
            int mid = (left + right) / 2;
            if (arr[mid] >= x)
            {
                right = mid;
            }
            else
            {
                left = mid + 1;
            }
        }
        --left;
        while (k)
        {
            if (left >= 0 && right < n)
            {
                if (x - arr[left] <= arr[right] - x)
                {
                    --left;
                }
                else
                {
                    ++right;
                }
            }
            else if (left >= 0)
            {
                --left;
            }
            else
            {
                ++right;
            }
            --k;
        }
        return vector<int>(arr.begin() + left + 1, arr.begin() + right);
    }
};